package com.earthchen.demo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.earthchen.core.base.BaseController;
import com.earthchen.core.vo.ResultVO;
import com.earthchen.demo.domain.SysResource;
import com.earthchen.demo.dto.PageParamDTO;
import com.earthchen.demo.enums.ExceptionEnum;
import com.earthchen.demo.exception.AuthException;
import com.earthchen.demo.service.SysResourceService;
import com.earthchen.demo.util.TreeUtil;
import com.earthchen.demo.vo.MenuTreeNodeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 资源URL管理
 *
 * @author earthchen
 * @date 2018/9/7
 **/
@RestController
@RequestMapping("/resource")
public class ResourceController extends BaseController {

    @Autowired
    private SysResourceService resourceService;


    /**
     * 获取用户被授权菜单
     * <p>
     * 通过uid获取对应用户被授权的菜单列表,获取完整菜单树形结构
     *
     * @param request
     * @return
     */
    @GetMapping("/authorityMenu")
    public ResultVO getAuthorityMenu(HttpServletRequest request) {
        Long uid = Long.valueOf(request.getHeader("appId"));
        List<MenuTreeNodeVO> treeNodes = new ArrayList<>();
        List<SysResource> resources = resourceService.getAuthorityMenusByUserId(uid);

        for (SysResource resource : resources) {
            MenuTreeNodeVO node = new MenuTreeNodeVO();
            BeanUtils.copyProperties(resource, node);
            node.setId(resource.getId());
            node.setCreateTime(resource.getCreateTime());
            node.setUpdateTime(resource.getUpdateTime());
            treeNodes.add(node);
        }
        List<MenuTreeNodeVO> menuTreeNodes = TreeUtil.buildTreeBy2Loop(treeNodes, -1L);
        return ResultVO.success(menuTreeNodes);
    }


    /**
     * 获取全部菜单列
     *
     * @return
     */
    @GetMapping("/menus")
    public ResultVO getMenus() {

        List<MenuTreeNodeVO> treeNodes = new ArrayList<>();
        List<SysResource> resources = resourceService.getMenus();

        for (SysResource resource : resources) {
            MenuTreeNodeVO node = new MenuTreeNodeVO();
            BeanUtils.copyProperties(resource, node);
            treeNodes.add(node);
        }
        List<MenuTreeNodeVO> menuTreeNodes = TreeUtil.buildTreeBy2Loop(treeNodes, -1L);
        return ResultVO.success(menuTreeNodes);
    }


    /**
     * 增加菜单
     *
     * @param menu
     * @return
     */
    @PostMapping("menu")
    public ResultVO addMenu(@RequestBody SysResource menu) {

        boolean flag = resourceService.insert(menu);
        if (!flag) {
            throw new AuthException(ExceptionEnum.SAVE_MENUS_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 修改菜单
     *
     * @param menu
     * @return
     */
    @PutMapping("/menu")
    public ResultVO updateMenu(@RequestBody SysResource menu) {

        boolean flag = resourceService.update(menu, new EntityWrapper<SysResource>().where("id", menu.getId()));
        if (!flag) {
            throw new AuthException(ExceptionEnum.UPDATE_MENUS_ERROR);
        }
        return SUCCESS;
    }


    /**
     * 根据菜单ID删除菜单
     *
     * @param menuId
     * @return
     */
    @DeleteMapping("/menu/{menuId}")
    public ResultVO deleteMenuByMenuId(@PathVariable Long menuId) {

        Boolean flag = resourceService.deleteMenuByMenuId(menuId);
        if (!flag) {
            throw new AuthException(ExceptionEnum.DELETE_RESOURCE_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 获取API list
     * <p>
     * 需要分页,根据teamId判断,-1->获取api分类,0->获取全部api,id->获取对应分类id下的api
     *
     * @param teamId
     * @param pageParamDTO
     * @return
     */
    @GetMapping("/api/{teamId}")
    public ResultVO getApiList(@PathVariable Long teamId, PageParamDTO pageParamDTO) {

        List<SysResource> resources;
        if (teamId == -1L) {
            // -1 为获取api分类
            resources = resourceService.getApiTeamList();
            return ResultVO.success(resources);
        }
        PageHelper.startPage(pageParamDTO.getPage(), pageParamDTO.getSize());
        if (teamId == 0L) {
            // 0 为获取全部api
            resources = resourceService.getApiList();
        } else {
            // 其他查询teamId 对应分类下的apis
            resources = resourceService.getApiListByTeamId(teamId);
        }
        return ResultVO.success(wrapPageResult(resources));
    }


    /**
     * 增加API
     *
     * @param api
     * @return
     */
    @PostMapping("/api")
    public ResultVO addApi(@RequestBody SysResource api) {

        boolean flag = resourceService.insert(api);
        if (!flag) {
            throw new AuthException(ExceptionEnum.SAVE_API_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 修改API
     *
     * @param api
     * @return
     */
    @PutMapping("/api")
    public ResultVO updateApi(@RequestBody SysResource api) {
        boolean flag = resourceService.updateById(api);
        if (!flag) {
            throw new AuthException(ExceptionEnum.UPDATE_API_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 根据API_ID删除API
     *
     * @param apiId
     * @return
     */
    @DeleteMapping("/api/{apiId}")
    public ResultVO deleteApiByApiId(@PathVariable Long apiId) {
        boolean flag = resourceService.deleteMenuByMenuId(apiId);
        if (!flag) {
            throw new AuthException(ExceptionEnum.DELETE_RESOURCE_ERROR);
        }
        return SUCCESS;
    }


}
